﻿using MQTTnet.Protocol;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;

namespace ZX.MQTTServer.Common
{
    public class SubscriptionPersistence
    {
        private readonly string _filePath = "mqtt_subscriptions.json";
        private readonly List<StoredSubscription> _subscriptions = new();
        private readonly object _lock = new();

        public SubscriptionPersistence()
        {
            load();
        }

        public void AddOrUpdate(string clientId, string topic, MqttQualityOfServiceLevel qos)
        {
            lock (_lock)
            {
                _subscriptions.RemoveAll(s => s.ClientId == clientId && s.Topic == topic);
                _subscriptions.Add(new StoredSubscription
                {
                    ClientId = clientId,
                    Topic = topic,
                    Qos = qos
                });
                save();
            }
        }

        public void Remove(string clientId, string topic)
        {
            lock (_lock)
            {
                _subscriptions.RemoveAll(s => s.ClientId == clientId && s.Topic == topic);
                save();
            }
        }

        private void save()
        {
            lock (_lock)
            {
                string json = JsonSerializer.Serialize(_subscriptions, new JsonSerializerOptions { WriteIndented = true });

                File.WriteAllText(_filePath, json);
            }
        }

        public List<StoredSubscription> GetByClient(string clientId)
        {
            lock (_lock)
            {
                return _subscriptions.Where(s => s.ClientId == clientId).ToList();
            }
        }

        public List<StoredSubscription> GetAll()
        {
            lock (_lock)
            {
                return new List<StoredSubscription>(_subscriptions);
            }
        }

        private void load()
        {
            lock (_lock)
            {
                if (!File.Exists(_filePath))
                {
                    using FileStream fileStream = File.Create(_filePath);
                }

                try
                {
                    string json = File.ReadAllText(_filePath);
                    if (string.IsNullOrEmpty(json)) return;

                    List<StoredSubscription> data = JsonSerializer.Deserialize<List<StoredSubscription>>(json);
                    if (data != null) _subscriptions.AddRange(data);
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"[加载订阅失败] {ex.Message}");
                }
            }
        }
    }
}
